import * as mars3d from 'mars3d'
import type {
  addToolButtonsArgs,
  MapEmitType,
  MapStateType,
  MMapProps,
} from '@/components/MMap/types.ts'

export function addToolButtons<E extends MapEmitType, P extends MMapProps>(
  map: MapStateType['instance'],
  { props, emit }: addToolButtonsArgs<E, P>,
) {
  if (!map) return
  if (typeof props.toolButtons === 'boolean' && !props.toolButtons) {
    console.log('MMap props.toolButtons===false不展示')
    return
  }
  // 切换按钮选中状态，返回boolean
  const toggleClassToActive = (targetClass: string): boolean | undefined => {
    const layerButton = document.querySelector(targetClass)
    if (layerButton) {
      layerButton.classList.toggle('active')
    }

    return layerButton?.classList.contains('active')
  }

  const PositionButton = new mars3d.control.ToolButton({
    title: '地图复位',
    icon: '',
    className: 'tool_position_btn',
    click: () => {
      map.centerAt({ lat: 40.811382, lng: 116.96254, alt: 1179023, heading: 0, pitch: -90 })
    },
  })

  const LayerButton = new mars3d.control.ToolButton({
    title: '地图图层按钮',
    icon: '',
    className: 'tool_layer_btn',
    click: () => {
      emit('clickLayerBut', toggleClassToActive('.tool_layer_btn'))
    },
  })
  const QuestionButton = new mars3d.control.ToolButton({
    title: '问题类型',
    icon: '',
    className: 'tool_question_btn',
    click: () => {
      emit('clickQuestionBut', toggleClassToActive('.tool_question_btn'))
    },
  })
  // 线路按钮
  const LineButton = new mars3d.control.ToolButton({
    title: '矢量数据',
    icon: '',
    className: 'tool_line_btn',
    click: () => {
      emit('clickLineBut', toggleClassToActive('.tool_line_btn'))
    },
  })
  map.addControl(PositionButton)
  if (typeof props.toolButtons !== 'boolean' && props.toolButtons) {
    if (props.toolButtons.layer) {
      map.addControl(LayerButton)
    }
    if (props.toolButtons.line) {
      map.addControl(LineButton)
    }
    if (props.toolButtons.question) {
      map.addControl(QuestionButton)
    }
  }
}
